import java.util.Arrays;
import java.util.Comparator;


public class AnagramSort {

	//Write a method to sort an array of strings so that all the anagrams are next to each other.

	public static void sortAnagrams(String []array) {

		Arrays.sort(array, new AnagramComparator());
			
	}

	static class AnagramComparator implements Comparator<String> {


		public int compare(String s1, String s2) {

			if(s1 == null || s2 == null) {
			
				if(s1 == s2) {
					return 0;
				} else {
					return s1 == null ? -1 : 1;
				}
			}
			else {

				char[] array1 = s1.toLowerCase().toCharArray();
				char[] arrray2 = s2.toLowerCase().toCharArray();
				Arrays.sort(array1);
				Arrays.sort(arrray2);
				return String.valueOf(array1).compareTo(String.valueOf(arrray2));
			}
		}
	}
	
	public static void main(String []args) {
		
		String[] array = { "FTUI", "LOPF", null, "OOO", "AART", "UITF", "PPPO", "RATA", "FLOP", null, "FIUT"};
		
		for(String s : array) {
			System.out.print(s + " ");
		}
		
		System.out.println();
		
		sortAnagrams(array);
		
		for(String s : array) {
			System.out.print(s + " ");
		}
		
	}
}
